package com.site.springboot.core.service.impl;

import com.alibaba.fastjson2.JSON;
import com.site.springboot.core.entity.News;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;

/**
 * Project:springboot-project-news-publish-system
 * ClassName:RedisService
 * Package:com.site.springboot.core.service.impl
 * User:CWQ
 * Description:
 *
 * @Author 合肥-陈万琼
 * @Create 2024/5/30 16:09
 * @Version 1.0
 */
@Service
public class RedisService {
    @Resource
    private RedisTemplate redisTemplate;

    public void saveNewsToRedis(News news) {
        String newsId = String.valueOf(news.getNewsId());
        redisTemplate.opsForValue().set("news"+ newsId, JSON.toJSONString(news));
    }

    public News editNews(Long newsId) {
        Object o = redisTemplate.opsForValue().get("news" + newsId);
        String json = String.valueOf(redisTemplate.opsForValue().get("news" + newsId));
        if (!StringUtils.hasText(json)) {
            return null;
        }
        News news = JSON.parseObject(json, News.class);
        return news;
    }

    public void updateNews(News news) {
        redisTemplate.opsForValue().set("news" + news.getNewsId(), JSON.toJSONString(news));
    }

    public void deleteNews(Integer[] ids) {
        String[] keys = Arrays.stream(ids)
                .map(i -> "news" + i)
                .toArray(String[]::new);
        redisTemplate.delete(Arrays.asList(keys));
    }
}
